import * as SignalR from "@microsoft/signalr";
import { TokenStore } from "@/store/token.js";
import { BASE_URL } from "@/http/env.js";
import { requestLogout } from "@/http/apis/login.js";
import clearPinia from "@/utils/clearPinia.js";

// 处理BASE_URL
const baseUrl = BASE_URL.endsWith("/") ? BASE_URL.slice(0, -1) : BASE_URL;

const getToken = () => {
  return TokenStore().getToken;
};

// 初始化SignalR对象
const connection = new SignalR.HubConnectionBuilder()
  .configureLogging(SignalR.LogLevel.Information)
  .withUrl(`${baseUrl}/hubs/onlineUser?token=${getToken()}`, {
    transport: SignalR.HttpTransportType.WebSockets,
    skipNegotiation: true,
  })
  .withAutomaticReconnect({
    nextRetryDelayInMilliseconds: () => {
      return 5000; // 每5秒重连一次
    },
  })
  .build();

connection.keepAliveIntervalInMilliseconds = 15 * 1000; // 心跳检测15s
connection.serverTimeoutInMilliseconds = 30 * 60 * 1000; // 超时时间30m

// 启动连接
connection.start().then(() => {
  console.log("启动连接");
});
// 断开连接
connection.onclose(async () => {
  console.log("断开连接");
});
// 重连中
connection.onreconnecting(() => {
  ElNotification({
    title: "提示",
    message: "服务器已断线...",
    type: "error",
    position: "bottom-right",
  });
});
// 重连成功
connection.onreconnected(() => {
  console.log("重连成功");
});

connection.on("OnlineUserList", () => {});

connection.on("ForceOffline", async (data) => {
  console.log("强制下线", data);
  await connection.stop();

  await requestLogout();
  clearPinia();
  // 退出后跳转到登录页
  setTimeout(() => {
    uni.reLaunch({
      url: "/pages/login/login",
    });
  }, 500);
});

export { connection as signalR };
